/**
 * Created with IntelliJ IDEA.
 * User: mkadush
 * Date: 04.09.13
 * Time: 11:23
 * To change this template use File | Settings | File Templates.
 */
Ext.onReady(function() {
    var store3 = Ext.create('Ext.data.TreeStore', {
        proxy: {                        // указание типа и  источника данных
            type: 'ajax',   //  тип данных - ajax
            url: '../organization/jsonDynamic' //  урл источника данных
        },
        root: {
            id: 'myOrg',
            text: 'Органаизация',
            expanded: true
        }
    });



    var buildCtxMenu =function(){
        return new Ext.menu.Menu({
            items: [
                {
                    itemId: 'add'
//                  handler: onAdd
                },
                {
                    itemId: 'edit',
                  handler: onEdit
                },
                {
                    itemId: 'delete'
//                  handler: onDelete
                }
            ]
        });
    };



    var onCtxMenu = function(view, record, item, index, event){

        if(!this.ctxMenu){
            this.ctxMenu =buildCtxMenu();
        }
        var ctxMenu= this.ctxMenu;
        var addItem = ctxMenu.getComponent('add');
        var editItem = ctxMenu.getComponent('edit');
        var deleteItem = ctxMenu.getComponent('delete');

        addItem.setText('добавить узел');
        editItem.setText('отредактировать узел');
        deleteItem.setText('удалить узел');

        if(record.data.id=="myOrg"){
            editItem.disable();
            deleteItem.disable();
            addItem.enable();
        }else if(record.data.leaf==true){
            addItem.disable();
            editItem.enable();
            deleteItem.enable();
        }else{
            addItem.enable();
            editItem.enable();
            deleteItem.enable();
        }


        x = event.browserEvent.clientX;
        y = event.browserEvent.clientY;

        ctxMenu.showAt([x,y]);



    };

    var onCompleteEdit = function(treeEditor, newValue, oldValue) {
        var treePanel =  Ext.getCmp('treepanel');
        treePanel.el.mask('Saving...', 'x-mask-loading');

        var editNode = treeEditor.editNode;
        var editNodeId = editNode.id;
        Ext.Ajax.request({
            url    : '../organization/jsonDynamic',
            params : {
                id      : editNodeId,
                newName : newValue
            },
            success : function (response, opts) {
                treePanel.el.unmask();
                var responseJson = Ext.decode(response.responseText);
                if (responseJson.success !== true) {
                    editNode.setText(oldValue);
                    Ext.Msg.alert('An error occured with the server.');
                }
            },
            failure : function (response, opts) {
                treePanel.el.unmask();
                editNode.setText(oldValue);
                Ext.Msg.alert('An error occured with the server.');
            }
        });
    };

    var onEdit = function() {
        var treePanel = Ext.getCmp('treepanel');
        var selectedNode = treePanel.getSelectionModel().getSelection();

        if (! this.treeEditor) {
            this.treeEditor = new Ext.tree.TreeEditor(treePanel, {}, {
                cancelOnEsc     : true,
                completeOnEnter : true,
                selectOnFocus   : true,
                allowBlank      : false,
                listeners       : {
                    complete : onCompleteEdit
                }
            });
        }

        this.treeEditor.editNode = selectedNode;
        this.treeEditor.startEdit(selectedNode.ui.textNode);

    };

    var treePanel = Ext.create('Ext.tree.Panel', {
        store: store3,
        id: 'treepanel',
        rootVisible: true,
        title: 'Organization',
        renderTo: Ext.getBody(),
        border: false,
        width: 250,
        height: 500,
        useArrows: true,
        dockedItems: [{
            xtype: 'toolbar',
            items: [{
                text: 'Expand All',
                handler: function(){
                    treePanel.expandAll();
                }
            }, {
                text: 'Collapse All',
                handler: function(){
                    treePanel.collapseAll();
                }
            }]
        }],

        listeners: {
             render: function() {
             Ext.getBody().on("contextmenu", Ext.emptyFn, null, {preventDefault: true});
            },
            itemcontextmenu : onCtxMenu
       }
    });

});